package com.pl.handler.sensitive;

import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.digest.MD5;
import cn.hutool.crypto.symmetric.SM4;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


public abstract class SensitiveFieldHandler<T>
        extends BaseTypeHandler<T> {
    private static final Logger log = LoggerFactory.getLogger(SensitiveFieldHandler.class);


    private final IFieldCrypto fieldCrypto;


    public SensitiveFieldHandler(IFieldCrypto fieldCrypto) {
        this.fieldCrypto = fieldCrypto;
    }


    public void setNonNullParameter(PreparedStatement preparedStatement, int i, T t, JdbcType jdbcType) throws SQLException {
        preparedStatement.setString(i, this.fieldCrypto.encrypt((String) t));
    }


    public T getNullableResult(ResultSet resultSet, String s) throws SQLException {
        String columnValue = resultSet.getString(s);
        return StrUtil.isBlank(columnValue) ? (T) columnValue : (T) this.fieldCrypto.decrypt(columnValue);
    }


    public T getNullableResult(ResultSet resultSet, int i) throws SQLException {
        String columnValue = resultSet.getString(i);
        return StrUtil.isBlank(columnValue) ? (T) columnValue : (T) this.fieldCrypto.decrypt(columnValue);
    }


    public T getNullableResult(CallableStatement callableStatement, int i) throws SQLException {
        String columnValue = callableStatement.getString(i);
        return StrUtil.isBlank(columnValue) ? (T) columnValue : (T) this.fieldCrypto.decrypt(columnValue);
    }

    public static void main(String[] args) {
        String certificate_number = "420100000000000001";
        String name = "张三";
        String sex = "男";
        String nation = "汉";
        String address = "湖北省武汉市洪山区李桥一路虹桥家园A1栋1单元0101室";

        String key = "E4A1A744C319D42DF4D61725D13DE8AFC1B42B3EEA99A8935B74DC98BCBD7A15";
        SM4 sm4 = new SM4(MD5.create().digest(key));

        String encrypted_certificate_number = sm4.encryptHex(certificate_number);
        log.info("certificate_number => {}", encrypted_certificate_number);

        String encrypted_name = sm4.encryptHex(name);
        log.info("name => {}", encrypted_name);

        String encrypted_sex = sm4.encryptHex(sex);
        log.info("sex => {}", encrypted_sex);

        String encrypted_nation = sm4.encryptHex(nation);
        log.info("nation => {}", encrypted_nation);

        String encrypted_address = sm4.encryptHex(address);
        log.info("address => {}", encrypted_address);
    }
}


/* Location:              E:\code\common\cmsr-common-mybatis\1.0.0-SNAPSHOT\cmsr-common-mybatis-1.0.0-SNAPSHOT.jar!\com\cmsr\common\mybatis\handler\sensitive\SensitiveFieldHandler.class
 * Java compiler version: 8 (52.0)
 * JD-Core Version:       1.1.3
 */